import {createRouter, createWebHistory} from "vue-router";
import Layout from "@/layout/ELayout.vue";
import {useRouteTagStore,useLoginStore} from "@/store/index";
import {storeToRefs} from "pinia";
import {ref,reactive} from "vue";
import systemRoutes from "@/router/module/System.js";
import videoRoutes from "@/router/module/video.js";
import interactionRoutes from "@/router/module/Interaction"
const routes = [
    {
        name: 'index',
        path: "/",
        redirect: "/video",
        component: Layout,
        children: [
            videoRoutes,
            interactionRoutes,
            systemRoutes,
            {
                name: "profile",
                path: "/profile",
                component: () => import("@/views/center/Profile.vue"),
                meta: {
                    icon: "User",
                    title: "个人中心",
                    isMenu: true
                },
                isHidden: false,
                children: []
            }
        ]
    },
    {
        name: 'login', path: "/login", meta: {isMenu: false, title: '登录'},
        component: () => import("@/views/Login.vue")
    },
    {
        path: '/:catchAll(.*)',
        component: () => import('@/views/NotFound.vue'),
    }

]

const router = createRouter({
    history: createWebHistory(),
    routes: routes
})

router.beforeEach((to, from, next) => {
    const {userIsLogin} = useLoginStore()
    if (to.path!=="/login" && !userIsLogin()) {
        next("/login")
    }else {
        next()
    }
})
router.afterEach((to, from) => {
    handleRouteTag(to)
})
/**
 * 路由导航标签处理
 * @param to
 */
function handleRouteTag(to) {
    if (to.meta.isMenu) {
        const routeTagStore = useRouteTagStore()
        const {navTags} = storeToRefs(routeTagStore)
        const {addRouteTag} = routeTagStore
        let navTag = {title: to.meta.title, path: to.path}
        if (!isExist(navTags.value, navTag)) {
            addRouteTag(navTag)
        }
    }
}


const isExist = (arr, o) => {
    return arr.find(item => item.title === o.title && item.path === o.path)
}
export default router

